package com.jerry.usbserial.util

import com.google.gson.JsonSyntaxException
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.io.EOFException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

abstract class ResultObserver<T> : Observer<T> {
    companion object {
        const val CONNECT_EXCEPTION = "网络连接异常，请检查您的网络状态"
        const val SOCKET_TIMEOUT_EXCEPTION = "网络连接超时，请检查您的网络状态，稍后重试"
        const val UNKNOWN_HOST_EXCEPTION = "与服务器连接失败"
        const val JSON_SYNTAX_EXCEPTION = "对象类型错误,无法解析"
        const val EMPTY_RESPONSE_EXCEPTION = "无效返回"
        const val UNKNOWN_EXCEPTION = "未知异常"
    }

    override fun onSubscribe(disposable: Disposable) {}

    override fun onComplete() {}

    override fun onNext(t: T) {
        handlerSuccess(t)
    }

    abstract fun handlerSuccess(data:T)

    override fun onError(throwable: Throwable) {
        var code = -1
        val msg = when (throwable) {
            is SocketTimeoutException -> SOCKET_TIMEOUT_EXCEPTION
            is ConnectException -> CONNECT_EXCEPTION
            is UnknownHostException -> UNKNOWN_HOST_EXCEPTION
            is EOFException -> EMPTY_RESPONSE_EXCEPTION
            is JsonSyntaxException -> JSON_SYNTAX_EXCEPTION
            is HttpException -> {
                code = throwable.code()
                throwable.message()
            }
            else -> throwable.message ?: UNKNOWN_EXCEPTION
        }
        handlerError(code, msg)
    }

    abstract fun handlerError(code: Int, msg: String)
}